package com.heima.comment.config;

import com.heima.comment.util.ApTokenThreadLocalUtil;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AppTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        log.info("评论拦截器，拦截的请求头用户ID:{}", userId);
        if (userId != null) {
            /**
             * 判断是否是游客登录
             */
            if (userId.equals(0)) {
                throw new CustomException(AppHttpCodeEnum.TOURIST_STATUS_NEED_LOGIN);
            }
            //存入到当前线程中
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            ApTokenThreadLocalUtil.setUser(apUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ApTokenThreadLocalUtil.clear();
    }
}
